from system.object import Object
from system.eventServer import eventServer

class KeyMap(Object):
    def __init__(self, parent, type = None, name = None):
        Object.__init__(self,parent,type,name)
        
        eventServer.register("keyDown",self.keyDown)
        eventServer.register("keyUp",self.keyUp)
        eventServer.register("mouseButtonDown",self.mouseButtonDown)
        eventServer.register("mouseButtonUp", self.mouseButtonUp)
        eventServer.register("joyButtonDown", self.joyButtonDown)
        eventServer.register("joyButtonUp", self.joyButtonUp)
        eventServer.register("joyAxisMotion", self.joyAxisMotion)
        
    def keyDown(self, cmd, args):
        self.dispatch("key_%s" % args['keyName'], True, 1)
        
    def keyUp(self, cmd, args):
        self.dispatch("key_%s" % args['keyName'], False, 0)
        
    def mouseButtonDown(self, cmd, args):
        self.dispatch("mouseButton_%d" % args['button'], True, 1)
        
    def mouseButtonUp(self, cmd, args):
        self.dispatch("mouseButton_%d" % args['button'], False, 0)
        
    def joyButtonDown(self, cmd, args):
        self.dispatch("joyButton_%d_%d" % (args['joy'],args['button']), True, 1)

    def joyButtonUp(self, cmd, args):
        self.dispatch("joyButton_%d_%d" % (args['joy'],args['button']), False, 0)
        
    def joyAxisMotion(self, cmd, args):
        if args['value'] > 0:
            sign = "pos"
        else:
            sign = "neg"
        value = abs(args['value'])
        bin = value > 0.5
        self.dispatch("joyAxis_%d_%d_%s" % (args['joy'],args['axis'],sign),bin,value)
        
    def dispatch(self, cmd, bin, value):
        if self.hasVar(cmd):
            args = {'bin':bin,'value':value}
            if self.hasVar(cmd + '_args'):
                args.update(self.getVar(cmd + '_args'))
            eventServer.pull(self.getVar(cmd),args)
